export default function (url, fd = new FormData()) {
    return new Promise(function (resolve, reject) {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response))
                } else {
                    if (xhr.status == 401) {
                        alert('未登录或登陆超时\n请重新登录');
                        location = '/login.html?url=' + encodeURIComponent(location.href)
                    } else {
                        alert('服务器错误')
                        reject(xhr.status);
                    }
                }
            }
        };

        //在url地址后加随机参数是为了避免服务器缓存
        xhr.open('post', url + '?a=' + new Date(), true);

        //读取token，添加token到请求头中
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));

        //fd是formData对象
        xhr.send(fd);
    })
}